<template>
  <el-upload
    class="upload"
    :class="{ hide: vdata.fileList.length >= limit }"
    v-model:file-list="vdata.fileList"
    :headers="header"
    :data="{ type: type }"
    list-type="picture-card"
    :accept="getAccept()"
    :action="getAction()"
    :on-change="onChange"
    :on-remove="onRemove"
    :on-preview="onPreview"
    :before-upload="onBeforeUpdate"
    :limit="limit"
  >
    <el-icon><Plus /></el-icon>
    <template #tip>
      <div>{{ label }}</div>
    </template>
  </el-upload>
</template>
<script setup lang="ts">
import type { UploadFile, UploadFiles, UploadProps, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadUrlOss, uploadUrlLocal } from '~/api/index'
const store = useAppStore()
const header = { Authorization: store.token, Platform: 'console' }
const props = defineProps({
  /**
   * 绑定的值，如果初始化绑定的是数组，默认推送数组，否则推送单个文本
   */
  modelValue: { type: [Array<string>, String], default: null },
  /**
   * 上传限制，最多允许上传的文件
   */
  limit: { type: Number, default: 1 },
  /**
   * 文件大小限制 单位M
   */
  size: { type: Number, default: 3 },
  /**
   * 文件类型，决定文件分类存放路径
   * 1 分类
   * 2 产品
   * 3 门店
   */
  type: { type: Number, default: 1 },
  /**
   * 文件上传的地址
   * 0本地
   * 1阿里云
   */
  uploadType: { type: Number, default: 0 },
  /**
   * 文件类型
   * 0 图片
   * 1 视频
   */
  fileType: { type: Number, default: 0 },
  /**
   * 建议图片大小
   */
  label: { type: String, default: '' }
})

const playImg = 'https://ring.victorycd.cn/oss/play.png'

const vdata = reactive({
  fileList: [] as UploadUserFile[]
})

// 获取文件类型
const getAccept = () => {
  switch (props.fileType) {
    case 1:
      return '.mp4,.mov,.wmv,.avi,.mkv'
    case 0:
      return '.jpg,.png,.jpeg,.gif'
    default:
      return '*.*'
  }
}

// 获取上传地址
const getAction = () => {
  switch (props.uploadType) {
    case 0:
      return uploadUrlLocal
    case 1:
    default:
      return uploadUrlOss
  }
}

// 上传限制
const onBeforeUpdate: UploadProps['beforeUpload'] = rawFile => {
  // 文件大小限制
  if (rawFile.size / 1024 / 1024 > props.size) {
    ElMessage.error(`文件大小不能超过${props.size}M`)
    return false
  }
  return true
}

// 点击删除
const onRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  successEmit(uploadFiles)
}

// 点击查看
const onPreview = (uploadFile: UploadFile) => {
  window.open(uploadFile.response ? (uploadFile.response as any).data : uploadFile.url)
}

// 上传回调
const onChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (uploadFile.status == 'success') {
    const { response } = uploadFile as any
    if (response.code == 200) {
      if (props.fileType === 0) {
        uploadFile.url = response.data
      } else {
        uploadFile.url = playImg
      }
      successEmit(uploadFiles)
    } else {
      uploadFile.status = 'fail'
      ElMessage.error(response.msg)
    }
  }
}

// 成功回调
const successEmit = (uploadFiles: UploadFiles) => {
  let files = [] as string[]

  uploadFiles.forEach(f => {
    if (f.status === 'success') {
      if (f.response) {
        files.push((f.response as any).data)
      } else {
        files.push(f.url!)
      }
    }
  })
  emit('update:modelValue', props.limit === 1 ? files[0] : files)
}

onMounted(() => {
  const modelValue = props.modelValue instanceof Array ? props.modelValue : props.modelValue ? [props.modelValue] : []
  vdata.fileList = modelValue.map((f: any) => ({ name: f, url: props.fileType === 1 ? playImg : f }))
})

const emit = defineEmits(['update:modelValue'])
</script>

<style lang="scss" scoped>
.hide {
  :deep(.ep-upload--picture-card) {
    display: none !important;
  }
}
</style>
